from flask import Blueprint, render_template, request
from applications.common.utils.rights import authorize
from flask_login import login_required
from applications.common.utils.validate import xss_escape
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.helper import ModelFilter
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.models import TargetModel
from applications.schemas import TarUrlOutSchema
from applications.extensions import db

spider_tar = Blueprint('spider', __name__, url_prefix='/spider/tar')


@spider_tar.get('/')
@authorize("spider:url:main", log=True)
def main():
    return render_template('spider/tar/main.html')


@spider_tar.get('/data')
@authorize("spider:url:main", log=True)
def table():
    tar_name = xss_escape(request.args.get("TarName", type=str))
    tar_url = xss_escape(request.args.get("TarUrl", type=str))
    mf = ModelFilter()
    if tar_name:
        mf.vague(field_name="name", value=tar_name)
    if tar_url:
        mf.vague(field_name="url", value=tar_url)

    tar = TargetModel.query.filter(mf.get_filter(TargetModel)).layui_paginate()
    count = tar.total

    return table_api(data=model_to_dicts(schema=TarUrlOutSchema, data=tar.items), count=count)


@spider_tar.get('/add')
@authorize("spider:url:add", log=True)
def add():
    return render_template('spider/tar/add.html')


@spider_tar.post('/save')
@authorize("spider:url:add", log=True)
def save():
    req = request.json
    details = xss_escape(req.get("details"))
    enable = xss_escape(req.get("enable"))
    TarName = xss_escape(req.get("TarName"))
    TarUrl = xss_escape(req.get("TarUrl"))
    tar = TargetModel(
        details=details,
        enable=enable,
        name=TarName,
        url=TarUrl
    )
    db.session.add(tar)
    db.session.commit()
    return success_api(msg="成功")


@spider_tar.put('/enable')
@authorize("spider:url:edit", log=True)
def enable():
    id = request.json.get('tarId')
    if id:
        res = enable_status(TargetModel, id)
        if not res:
            return fail_api(msg="出错了")
        return success_api(msg="启动成功")
    return fail_api("数据错误")


@spider_tar.put('/disable')
@authorize("spider:url:edit", log=True)
def dis_enable():
    _id = request.json.get('tarId')
    if _id:
        res = disable_status(TargetModel, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


@spider_tar.get('/edit/<int:id>')
@authorize("spider:url:edit", log=True)
def edit(id):
    t = get_one_by_id(model=TargetModel, id=id)
    return render_template('spider/tar/edit.html', target=t)


@spider_tar.put('/update')
@authorize("spider:url:edit", log=True)
def update():
    req_json = request.json
    id = req_json.get("tarId")
    data = {
        "url": xss_escape(req_json.get("TarUrl")),
        "name": xss_escape(req_json.get("TarName")),
        "enable": xss_escape(req_json.get("enable")),
        "details": xss_escape(req_json.get("details"))
    }
    tar = TargetModel.query.filter_by(id=id).update(data)
    db.session.commit()
    if not tar:
        return fail_api(msg="更新角色失败")
    return success_api(msg="更新角色成功")


@spider_tar.delete('/remove/<int:id>')
@authorize("spider:url:delete", log=True)
def remove(id):
    t = TargetModel.query.filter_by(id=id).delete()
    db.session.commit()
    if not t:
        return fail_api(msg="目标删除失败")
    return success_api(msg="目标删除成功")


@spider_tar.delete('/batchRemove')
@authorize("spider:url:delete", log=True)
def batch_remove():
    ids = request.form.getlist("ids[]")
    for id in ids:
        t = TargetModel.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
